#! /bin/bash
read -p "请输入要转换的m3u文件：" m3u_name
if [[ -z "$m3u_name" ]]; then
	echo "输入为空，请重新输入！"
	exit 1
elif ! ls | grep -q "$m3u_name"; then
	echo "输入的文件当前目录不存在，请检查后重新输入！"
	exit 1
elif ! echo "$m3u_name" | grep -q ".m3u"; then
	echo "输入的不是m3u文件，请检查后重新输入！"
	exit 1
else
	sed -n '4,$p' "$m3u_name" > "$m3u_name.tmp"
	sed -n '0~2p' "$m3u_name.tmp" > "偶数行.txt"
	sed -n '1~2p' "$m3u_name.tmp" > "奇数行.txt"
	sed -i 's/,/:/' "奇数行.txt"
	cut -d ":" -f 3- "奇数行.txt" > "台名称.txt"
	sed -i -e 's/\r$//' "台名称.txt" -e 's/\r$//' "偶数行.txt"
	new_name="${m3u_name%.m3u*}.txt"
	paste -d "," "台名称.txt" "偶数行.txt" > "$new_name"
	sed -i "1 i ${m3u_name%.m3u*},#genre#" "$new_name"
	status=$?
fi
if [[ "$status" -eq 0 ]]; then
	echo "转换成功！新文件名为 $new_name"
	rm "$m3u_name.tmp" "偶数行.txt" "奇数行.txt" "台名称.txt"
else
	echo "转换失败，请重试！"
fi
